package com.photons.artp.utils

import android.content.Context
import android.text.TextUtils
import com.photons.artp.App
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException

class NetUtils {
    companion object {
        //获取本地IPv4
        fun getLocalIPv4(): String {
            try {
                val en = NetworkInterface.getNetworkInterfaces()
                while (en.hasMoreElements()) {
                    val intf = en.nextElement()
                    val enumIpAddr = intf.inetAddresses
                    while (enumIpAddr.hasMoreElements()) {
                        val inetAddress = enumIpAddr.nextElement()
                        if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                            return inetAddress.hostAddress.toString()
                        }
                    }
                }
            } catch (ex: SocketException) {
            }
            return "0.0.0.0"
        }

        fun getPeerIP(): String {
            val sp = App.instance?.getSharedPreferences("def", Context.MODE_PRIVATE)
            val recent = sp?.getString("peerIP", "") ?: ""
            return if (TextUtils.isEmpty(recent)) {
                getLocalIPv4();
            } else {
                recent
            }
        }

        fun savePeerIP(ip: String) {
            val sp = App.instance?.getSharedPreferences("def", Context.MODE_PRIVATE)
            sp?.edit()?.putString("peerIP", ip)?.apply()
        }
    }
}